<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Article;

class ArticleController extends Controller
{
    //
    public function index(){
        return view('admin/article/index')->withArticles(Article::paginate(15));
    }

    public function create(){
        return view('admin/article/create');
    }

    public function store(Request $request){
        $this->validate($request, [
            'title'=>'required|unique:articles|max:255',
            'body'=>'required',
        ]);

        $article = new Article();
        $article->title = $request->get('title');
        $article->body = $request->get('body');
        $article->user_id = $request->user()->id;

        if($article->save()){
            return redirect('admin/article');
        }else{
            return redirect()->withErrors('新增失败！');
        }
    }

    public function show($id){
        $article = Article::with('hasManyComments')->find($id); 
        $title = $article->title;
        return view('admin/article/show', ['article' => $article, 'title' => $title]);
    }

    public function edit($id) { 
        $article = Article::find($id); 
        return view('admin/article/edit')->with('article', $article); 
    }

    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'title' => 'required|unique:articles,title,'.$id.'|max:255',
            'body' => 'required', 
        ]);

        $article = Article::find($id);
        $article->title = $request->get('title');
        $article->body = $request->get('body');

        if ($article->save()) {
            return redirect('admin/article');
        } else {
            return redirect('admin/article')->withErrors('更新失败！');
        }
    }

    public function destroy($id){
        $article = Article::find($id);  
        if($article->delete()){
            return redirect('admin/article')->withErrors('删除成功！');
        }else{
            return redirect('admin/article')->withErrors('删除失败！');
        }
    }
    
}
